using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace Locations.API.Infrastructure.AuthExtension.TestAuth
{
    /// <summary>
    /// 自定义身份验证Handle
    /// </summary>
    public class TestAuthenticationHandler : AuthenticationHandler<TestAuthenticationOptions>
    {
        public TestAuthenticationHandler(IOptionsMonitor<TestAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
        { }

        public int ForbidCount { get; set; }
        public int ChallengeCount { get; set; }
        public int AuthenticateCount { get; set; }

        protected override Task HandleChallengeAsync(AuthenticationProperties properties)
        {
            ChallengeCount++;
            return Task.CompletedTask;
        }

        protected override Task HandleForbiddenAsync(AuthenticationProperties properties)
        {
            ForbidCount++;
            return Task.CompletedTask;
        }

        /// <summary>
        /// 身份验证
        /// </summary>
        /// <returns></returns>
        protected override Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            AuthenticateCount++;
            var principal = new ClaimsPrincipal(Options.Identity);
            return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principal, new AuthenticationProperties(), Scheme.Name)));
        }
    }
}
